package com.tfb.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

public class HeaderUtil {

    public static Credentials getCredentials(HttpServletRequest req) {
        String header = req.getHeader("Authorization");
        if (header == null)
            return null;
        if (!header.startsWith("Basic"))
            return null;

        byte[] authBytes = Base64.decodeBase64(header.substring("Basic".length()).trim().getBytes());
        String auth = new String(authBytes);
        if (auth == null || auth.length() <= 0)
            return null;
        int sep = auth.indexOf(":");
        String username = auth.substring(0, sep);
        String password = auth.substring(sep + 1);
        return new Credentials(username, password);
    }

    public static void unauthorized(HttpServletResponse resp) {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //For avoiding CSRF
        resp.addHeader("WWW-Authenticate", "Basic realm=\"tfb\"");
    }

    public static void addXContentTypeOptions(HttpServletResponse resp) {
        resp.addHeader("X-Content-Type-Options", "nosniff");
    }

   // public static ThreadLocal<Auth>auth = new ThreadLocal<Auth>();
    // public static ThreadLocal<SimpleThreadAuth>simpleAuth = new ThreadLocal<SimpleThreadAuth>();
}
